<script setup lang="ts">
import type { CellValueChangedEvent } from 'ag-grid-community'

import { reactive, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { AgGridVue } from 'ag-grid-vue3'
import { Button, message } from 'ant-design-vue'
import dayjs from 'dayjs'

import { batchSubmitApproval } from '#/api/purchase'
import rightColumnActionsRenderer from '#/views/backend/spuBom/components/agGridVueComponents/rightColumnActionsRenderer.vue'

import selpurchaseBom from './selpurchaseBom.vue'
import submitApproval from './submitApproval.vue'

import 'ag-grid-enterprise'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'

const materialGridRef = ref()

const templateData = {
  material_name: '',
  id: '',
  scene: 'purchase_bom_detail',
}
const info = reactive({
  formData: [] as any,
})

const Options: any = ref({
  detailRowAutoHeight: true,
  components: { rightColumnActionsRenderer, selpurchaseBom },
  columnDefs: [
    {
      headerName: '物料名称',
      field: 'material_name',
      editable: true,
      width: 300,
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellEditor: 'selpurchaseBom', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '采购单号',
      field: 'caigou_id',
      editable: false,
      cellDataType: 'text',
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '手工单号',
      field: 'purchase_sn',
      editable: false,
      cellDataType: 'text',
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '交货日期',
      field: 'dead_line',
      editable: true,
      cellDataType: 'date',
      cellClass: 'borderCcc',
      suppressMenu: true, // 仅此列不显示菜单按钮
      // cellRenderer: 'selectDate', // 使用自定义渲染组件
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '下单数量',
      field: 'confirm_num',
      editable: true,
      cellClass: 'borderCcc',
      cellDataType: 'text',
      suppressMenu: true, // 仅此列不显示菜单按钮

      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '采购单价',
      field: 'price',
      editable: true,
      cellClass: 'borderCcc',
      cellDataType: 'text',
      suppressMenu: true, // 仅此列不显示菜单按钮

      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '修改原因',
      field: 'remark',
      editable: true,
      width: 700,
      cellClass: 'borderCcc',
      cellDataType: 'text',
      suppressMenu: true, // 仅此列不显示菜单按钮
      cellStyle: {
        textAlign: 'center',
      },
    },
    {
      headerName: '操作',
      cellClass: 'borderCcc',
      editable: false,
      suppressMenu: true, // 仅此列不显示菜单按钮
      field: 'actions',
      // pinned: 'right', // 固定在右侧

      cellRenderer: 'rightColumnActionsRenderer', // 使用自定义渲染组件
      cellRendererParams: {
        context: {
          buttons: ['del'],
          deleteRow: (index) => {
            // 传递删除方法到渲染器
            const pData = [...info.formData]

            pData.splice(index, 1)
            info.formData = pData
          },
        },
      },
    },
  ],
  rowData: [],
  // height: '500px', // 设置整个表格的高度为400px
  domLayout: 'autoHeight', // 设置表格自适应高度
  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  defaultColDef: {
    editable: true, // 必须设置为可编辑，否则无法复制
  },
  suppressClickEdit: false, // 禁用单击即编辑
  rowDragManaged: true, // 启用托管拖拽
  editType: 'cellEditor', // fullRow,cellEditor
  getContextMenuItems: (params: any) => {
    console.log(params)
    const result = [
      'export',
      {
        name: '向上插入一行',
        action: () => {
          const newRow = { ...templateData }
          const selectedNode = params.node
          const mData = [...info.formData]
          const startIndex = selectedNode ? Math.max(selectedNode.rowIndex, 0) : 0
          mData.splice(startIndex, 0, newRow)
          info.formData = mData
        },
      },
      {
        name: '向下插入一行',
        action: () => {
          const newRow = { ...templateData }
          const selectedNode = params.node
          const mData = [...info.formData]
          // let indexConfig = selectedNode?{ addIndex: (selectedNode.rowIndex + 1)}:{};
          // params.api.applyTransaction({ add: [newRow],...indexConfig})

          const startIndex = selectedNode ? selectedNode.rowIndex + 1 : 0
          mData.splice(startIndex, 0, newRow)
          info.formData = mData
        },
      },
      {
        name: '删除选中行',
        action: () => {
          const getCellRanges = params.api.getCellRanges()[0]
          const infoStartRow = getCellRanges.startRow.rowIndex
          const infoEndRow = getCellRanges.endRow.rowIndex
          const startRow = Math.max(infoEndRow, infoStartRow)
          const endRow = Math.min(infoEndRow, infoStartRow)
          const pData = [...info.formData]
          for (let i = startRow; i >= endRow; i--) {
            pData.splice(i, 1)
          }
          info.formData = pData
        },
      },
    ]
    return result
  },
  onRowDragEnd: (event: any) => {
    const newOrder: any = []
    event.api.forEachNode((node: any) => {
      newOrder.push(node.data)
    })
    info.formData = newOrder // 更新响应式数组
  },
  onCellValueChanged: (params: CellValueChangedEvent) => {
    const rowIndex: any = params.rowIndex
    const field: any = params.colDef.field
    const newValue: any = params.newValue
    // 更新响应式数据
    const updated: any = [...info.formData]
    updated[rowIndex] = {
      ...updated[rowIndex],
      [field]: newValue,
    }
    info.formData = updated
  },
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[95%] h-[100%]',
  appendToMain: true,
  onCancel() {
    modalApi.close()
  },
  onConfirm() {
    materialGridRef.value?.api?.stopEditing()
    const data = JSON.parse(JSON.stringify(info))
    // 格式化日期
    const formattedData = data.formData.map((item: any) => {
      const formattedItem = { ...item }
      if (formattedItem.dead_line) {
        // formattedItem.dead_line = dayjs(formattedItem.deliveryDate).format('YYYY-MM-DD')
        formattedItem.dead_line = dayjs(formattedItem.dead_line).format('YYYY-MM-DD') // 输出: 2021-02-27
      }
      return formattedItem
    })

    const apiData = {
      formData: {
        isConfirmSubmit: info.formData.isConfirmSubmit,
        scene: 'PurchaseBomDetail', // 将场景值从purchase_bom_detail改为PurchaseBomDetail
        list: formattedData.map((item: any) => ({
          id: String(item.id), // 确保id是字符串格式
          updateData: [
            { field: 'dead_line', value: item.dead_line || '' },
            { field: 'confirm_num', value: String(item.confirm_num) || '' },
            { field: 'price', value: item.price || '' },
          ],
          ...(item.remark ? { remark: item.remark } : {}), // 只在remark有值时才包含该字段
        })),
      },
    }
    batchSubmitApproval(apiData).then((res: any) => {

      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
      } else if (res.data.code === 201) {
        submitApprovalModalApi.setData({ data: res.data.data }).open();
      }else {
        message.error(res.data.msg)
      }
    })
  },
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return
  },
})

function handadd() {
  const newRow = JSON.parse(JSON.stringify(templateData))
  newRow.id = info.formData.length
  const mData = [...info.formData]
  mData.push(newRow)
  info.formData = mData
}

const [submitApprovalModal, submitApprovalModalApi] = useVbenModal({
  connectedComponent: submitApproval,
})

function handleFilePushData(event: any) {
    info.formData.isConfirmSubmit = 1
    modalApi.onConfirm()
}
</script>

<template>
  <div>
    <submitApprovalModal @push-data="handleFilePushData" />
    <Modal title="物料采购单明细修改">
      <div>
        <Button type="primary" @click="handadd" style="margin-bottom: 10px">添加行</Button>
        <AgGridVue ref="materialGridRef" :row-data="info.formData" :grid-options="Options" class="ag-theme-quartz" style="flex-grow: 1; overflow-y: scroll" borderd />
      </div>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.borderCcc) {
  // 表体单元格右边框
  border-right: 1px solid #ccc;
}
:deep(.ag-cell, .ag-full-width-row .ag-cell-wrapper.ag-row-group) {
  // 表体左右内边距
  padding: 0;
}

:deep(
//.ag-theme-balham .ag-header-cell-label,
//.ag-theme-alpine .ag-header-cell-label,
.ag-theme-quartz .ag-header-cell-label) {
  // 表头标题居中
  justify-content: center;
  display: flex;
  align-items: center;
}
:deep(.ag-header-cell, .ag-header-group-cell) {
  // 表头左右内边距
  padding: 0;
}
:deep(.ag-ltr .ag-header-viewport .ag-header-cell-resize::after) {
  // 表头右边框
  left: calc(50% - 0px);
}
:deep(.ag-header-cell-resize::after) {
  // 表头右边框
  width: 1px;
  height: 100%;
  top: 0;
}
</style>
